package com.example.diet_sport.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.diet_sport.entity.sport;
import com.example.diet_sport.mapper.foodMapper;
import com.example.diet_sport.mapper.sportMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 伽蓝尘
 * @create 2023-06-03 15:50
 */
@RequestMapping("/sport")
@RestController
@CrossOrigin
public class sportController {

    @Autowired
    private sportMapper sportMapper;

    /**
     * 添加食物
     * @param sport
     */
    @PostMapping("/add")
    @ResponseBody
    public void add(sport sport) {
        int i =  sportMapper.insert(sport);
        if(i>0){
            System.out.println("注册成功");
        }else{
            System.out.println("注册失败");
        }
    }


    @GetMapping("/sportList")
    public List<sport> getSportList() {
        return sportMapper.selectList(null);
    }


    @PostMapping("/update")
    public void changeFoodById(sport sport) {
        sportMapper.updateById(sport);
    }



    @ResponseBody
    @PostMapping("/delete")
    public int deleteByName(String name ) {
        int id = queryIdByName(name);
        return sportMapper.deleteById(id);
    }

    /**
     * 模糊查询
     * @param key
     * @return
     */
    @GetMapping("/search")
    public List<sport>searchSport(String key){
        QueryWrapper<sport> wrapper = new QueryWrapper<>();
        wrapper.like("name",key);
        List<sport> sports = sportMapper.selectList(wrapper);
        System.out.println(sports);
        return sports;
    }

    @Transactional
    @GetMapping("/getid")
    public int queryIdByName(String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("name",name);
        return sportMapper.selectByMap(map).get(0).getId();
    }
}


